import Vue from 'vue'
import Vuex from 'vuex';
import api from "../api/index.js";
import HomeState from './home.js';
import AddresState from './address.js';
Vue.use(Vuex)
const store = new Vuex.Store({
	modules:{
		home:HomeState,
		address:AddresState,
	},
    state:{
        hasLogin:false,//是否登录,
        user:"",//用户信息
        token:"",
		location:'',//位置信息
		city:'',//城市
    },
    mutations:{
		// 存储我的位置信息
		setCity(state,info){
			state.city = info;
			uni.setStorageSync('city',info);
		},
		// 存储我的位置信息
		setLocation(state,info){
			state.location = info;
			uni.setStorageSync('location',JSON.stringify(info));
		},
        //登录 
        login(state,user){
            state.hasLogin=true;
            state.user=user || null;
        },
        getToken(state,token){
            console.log(token)
            state.token=token;
        },
         /*更新用户信息*/ 
	    getUserInfo(state,item){
            state.user=item;
            state.hasLogin=true;
        },
    },
    actions:{
		setCity({commit},info){
			commit('setCity',info);
		},
		setLocation({commit},info){
			commit('setLocation',info);
		},
        getUser(ctx,item){
            api.getUserInfo().then(res=>{
				debugger
                if(!res.user_id){
                    uni.showToast({
                        icon:"none",
                        title: '登录失败',
                        duration: 3000,
                        
                    });
                    return 
                }
                if(res.head_pic.indexOf('public')==1){
                    res.head_pic = config.host+res.head_pic;
                }
                console.log(res)
                ctx.commit('getUserInfo',res)
            })
        },     
    },
	getters:{
		getLocation(state){
			try {
				let val = uni.getStorageSync('location') || '{}';
				let location = state.location || JSON.parse(val);
				// 确保返回有效的经纬度对象
				if(location && location.latitude && location.longitude){
					return location;
				}
				return { latitude: 0, longitude: 0 };
			} catch (e) {
				console.error("获取位置信息失败：", e);
				return { latitude: 0, longitude: 0 };
			}
		},
		getCity(state){
			try {
				// 优先使用state中的城市，然后是缓存中的城市，最后是默认值
				let val = uni.getStorageSync('city');
				let city = state.city || val;
				return city || '北京';
			} catch (e) {
				console.error("获取城市信息失败：", e);
				return '北京';
			}
		}
	}
})

export default store